/**
 * @author Nicolas Lusa (lusan@usi.ch)
 */
package ch.usi.inf.pf2.gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;

import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JToggleButton;
import javax.swing.JToolBar;

import ch.usi.inf.pf2.file.interaction.InstructionWriter;
import ch.usi.inf.pf2.gui.action.DeleteAction;
import ch.usi.inf.pf2.gui.action.LoadAction;
import ch.usi.inf.pf2.gui.action.NewAction;
import ch.usi.inf.pf2.gui.action.QuitAction;
import ch.usi.inf.pf2.gui.action.ResetAction;
import ch.usi.inf.pf2.gui.action.RunAction;
import ch.usi.inf.pf2.gui.action.SaveAction;
import ch.usi.inf.pf2.gui.action.SelectAllAction;
import ch.usi.inf.pf2.gui.action.StepRunAction;
import ch.usi.inf.pf2.gui.tool.Tool;


public final class CircuitFrame extends JFrame {
	private static JFileChooser fileChooser = new JFileChooser(System.getProperty("user.dir"));
	private final CircuitFrame circuitFrame;
    private final Model model;
    private JPanel editor;
    
    public CircuitFrame(final Model model) {
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
    	circuitFrame = this;
        this.model = model;
        setTitle("Java Circuits");
        setSize(new Dimension(1000, 700));
        setMinimumSize(new Dimension(800, 450));
        
        final JMenuBar menuBar = new JMenuBar();
        final JMenu fileMenu = new JMenu("File");
        final JMenu editMenu = new JMenu("Edit");
        final JMenu runMenu = new JMenu("Run");
        fileMenu.add(new NewAction());
        fileMenu.add(new SaveAction(this, model));
        fileMenu.add(new LoadAction(this, model));
        fileMenu.add(new QuitAction(this, model));
        editMenu.add(new SelectAllAction(model));
        editMenu.add(new DeleteAction(this, model));
        runMenu.add(new RunAction(this, model));
        runMenu.add(new StepRunAction(this, model));
        runMenu.add(new ResetAction(this, model));
        menuBar.add(fileMenu);
        menuBar.add(editMenu);
        menuBar.add(runMenu);
        setJMenuBar(menuBar);
        
        
        final JToolBar toolBar = new JToolBar();
        add(toolBar, BorderLayout.WEST);
        toolBar.setLayout(new BoxLayout(toolBar, BoxLayout.Y_AXIS));
        toolBar.setFloatable(false);

        final CircuitArea drawingArea = new CircuitArea(this, model);
        
        drawingArea.setPreferredSize(new Dimension(1000, 600));
		final JScrollPane s = new JScrollPane(drawingArea);
        s.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    	s.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        add(s, BorderLayout.CENTER);
        
        //Create legend.
        JPanel northPanel = new JPanel();
        northPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
        JPanel legendPanel = new JPanel();
        legendPanel.setBackground(Color.WHITE);
        
        ImageIcon iconGreen = new ImageIcon(getClass().getResource("icons/green.png"));
        ImageIcon iconRed = new ImageIcon(getClass().getResource("icons/red.png"));
        ImageIcon iconBlue = new ImageIcon(getClass().getResource("icons/blue.png"));
        ImageIcon iconBlack = new ImageIcon(getClass().getResource("icons/black.png"));
        JLabel comment = new JLabel("<html><i>Legend: </i></html>");
        JLabel green = new JLabel("<html><font color=green> TRUE</font></html>", iconGreen, JLabel.CENTER);
        JLabel blue = new JLabel("<html><font color=blue> FALSE</font></html>", iconBlue, JLabel.CENTER);
        JLabel black = new JLabel("<html><font color=black> UNKNOWN</font></html>", iconBlack, JLabel.CENTER);
        JLabel red = new JLabel("<html><font color=red> SELECTED</font></html>", iconRed, JLabel.CENTER);
        legendPanel.add(comment);
        legendPanel.add(green);
        legendPanel.add(blue);
        legendPanel.add(black);
        legendPanel.add(red);
        northPanel.add(legendPanel);
        add(northPanel, BorderLayout.NORTH);

        // create tool buttons
        final ButtonGroup group = new ButtonGroup();
        boolean first = true;
        for (final Tool tool : drawingArea.getTools()) {
            final JToggleButton button = new JToggleButton();
            //button.setText(tool.getName());
            button.setToolTipText(tool.getName());
            button.setIcon(tool.getIcon());
            toolBar.add(button);
            group.add(button);
            if (first) {
                button.setSelected(true);
                first = false;
            }
            button.addActionListener(new ActionListener() {
                public void actionPerformed(final ActionEvent ev) {
                    drawingArea.setCurrentTool(tool);
                }
            });
            
            button.addMouseListener(new MouseAdapter() {
            	public void mouseEntered(final MouseEvent ev) {
            		button.setIcon(tool.getIconMouseOver());
            	}
            });
            
            button.addMouseListener(new MouseAdapter() {
            	public void mouseExited(final MouseEvent ev) {
            		button.setIcon(tool.getIcon());
            	}
            });
        }
        
        //toolBar.addSeparator();
        
        toolBar.add(new SelectAllAction(model));
        toolBar.add(new DeleteAction(this, model));
        toolBar.add(new RunAction(this, model));
        toolBar.add(new StepRunAction(this, model));
        
        JPanel southPanel = new JPanel();
        //southPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
        editor = new JPanel();
        editor.setPreferredSize(new Dimension(800, 80));
        editor.setLayout(new BoxLayout(editor, BoxLayout.Y_AXIS));
        editor.setBackground(Color.WHITE);
        
       
        //JScrollPane scrollEditor = new JScrollPane(editor);
        southPanel.add(editor);
        add(southPanel, BorderLayout.SOUTH);
        
		addComponentListener(new ComponentAdapter() {
			public void componentResized(ComponentEvent e) {
				 System.out.println("componentResized");
				 drawingArea.setPreferredSize(drawingArea.getSize());
				 s.revalidate();
			}
		});

        // register listeners
        addWindowListener(new WindowAdapter() {
        	public void windowClosing(final WindowEvent ev) {
            	// TODO: Open a dialog to as the user whether they really want to quit
            	int result = JOptionPane.showConfirmDialog(getCircuitFrame(), "Do you want to save before exit?");
        		if(result == 2) {
        		}
        		
        		else if(result == 1) {
        			circuitFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        		}
        		else if(result == 0) {
        			if(model.getCircuit() != null) {
        	            int returnVal = fileChooser.showSaveDialog(circuitFrame);
        	    
        	            if(returnVal != JFileChooser.APPROVE_OPTION) {
        	                return;
        	            }
        	            File selectedFile = fileChooser.getSelectedFile();
        	            InstructionWriter writer = new InstructionWriter(selectedFile.getAbsolutePath(), model.getCircuit().getShapes());
        	            circuitFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        			}	
        		}
        	}
        });
    }
    
    public CircuitFrame getCircuitFrame() {
    	return this;
    }
    
    //get model
    public Model getModel() {
    	return model;
    }
    
    //getEditor
    public JPanel getEditor() {
    	return editor;
    }
    
    public void setEditor(final JLabel waveformLabel) {
		editor.add(waveformLabel);
		//editor.validate();
		//editor.repaint();
    }

}


